#-*- coding: utf-8 -*-
import os
import logging
import traceback

from nose.util import tolist

from selenose.grid import Grid
from selenose.web import Djangos
from selenose.consts import LOGGER, LOCALHOST
from selenose.tools import get_available_port
from selenose.server import server_start, server_stop

# Get a logger
logger =  logging.getLogger('%s.%s' % (LOGGER, __name__))

def environ(options):
    '''Set environ'''
    # Set configuration
    os.environ['SELENOSE_SETTINGS_MODULE'] = options.settings
    # Set settings
    os.environ['DJANGO_SETTINGS_MODULE'] = 'selenose.settings'

def startup(options, nbrs):
    '''Start servers'''
    # Create the grid
    grid = Grid(options.grid, options.java, tolist(options.libs), options.work)
    # Create the web server
    djangos = Djangos(options.settings, LOCALHOST, nbrs, options.work)
    # Start grid
    grid.start()
    # Try to start web server
    try: djangos.initialize()
    # If start failed, close grid
    except BaseException, e:
        # Try to stop grid
        try: grid.stop()
        # Log only if error to keep the first trace
        except BaseException: logger.error(traceback.format_exc())
        # Propagate
        raise e
    # Snapshot all servers
    djangos.snapshot()
    # Create the server
    server = server_start(LOCALHOST, get_available_port(), grid, djangos)
    # Return all servers
    return grid, djangos, server

def shutdown(keep, grid, djangos, server):
    '''Shutdown'''
    # Stop grid
    grid.stop()
    # Check if clean
    if not keep:
        # Clean web server
        djangos.clean()
        # Clean grid
        grid.clean()
    # Stop the server
    server_stop(server)

